package com.jayqqaa12.robot.lottery;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import weiboclient4j.WeiboClientException;
import weiboclient4j.oauth2.SinaWeibo2AccessToken;

import com.jayqqaa12.jbase.util.L;
import com.jayqqaa12.robot.Consts;
import com.jfinal.ext.plugin.config.ConfigKit;

public class TokenService {

	// 获取 token 的 另一张方式 需要登录。。
	public static String url = "https://api.weibo.com/2/oauth2/authorize?client_id=" + Consts.SINA_APPID
			+ "&response_type=token&display=js&redirect_uri=https://api.weibo.com/oauth2/default.html";

	private static Pattern pattern = Pattern.compile("token\":\"([\\s\\S]+)\",\"r");
	private static Pattern pattern2 = Pattern.compile("remind_in\":\"([\\s\\S]+)\",");

	private long pastDate = 0;

	public String getToken(List<Cookie> cookies) {

		try {
			

			// FIXME 方案1 自动登录 选择不好使了

			// 方案2 模拟登录 获取 token 12小时要重新获取一次token

			DefaultHttpClient client = new DefaultHttpClient();

			for (Cookie c : cookies) {
				client.getCookieStore().addCookie(c);
			}

			HttpGet get = new HttpGet(url);
			HttpResponse response2 = client.execute(get);
			System.out.println(response2.getStatusLine());
			HttpEntity entity2 = response2.getEntity();
			String data = EntityUtils.toString(entity2);
			Matcher m = pattern.matcher(data);
			if (m.find()) {
				String result = m.group();
				result = result.replace("token\":\"", "");
				result = result.replace("\",\"r", "");
				
				System.out.println(result);

				Matcher m2 = pattern2.matcher(data);
				if (m2.find()) {
					String time = m2.group().replace("remind_in\":\"", "").replace("\",", "");
					pastDate = Integer.parseInt(time) * 1000 + System.currentTimeMillis();
					L.i("获取 token 成功  tokean = " + result + " time =" + time);
				}
				return result;
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			L.i("获取token失败" + e.getMessage());
		}

		return null;

	}

 

}